package main

import (
	"encoding/json"
	"go.manyji.com/lib/app"
	"go.manyji.com/lib/config"
	"go.manyji.com/lib/log"
	_ "go.manyji.com/lib/log/filelog"
	_ "go.manyji.com/lib/systemd/autostart"
	"net/http"
	_ "net/http/pprof"
	"path/filepath"
	"sieve_agent_server/lib/server"
)

var (
	fTlsCert      = config.String("tls.cert", "", "tls cert file")
	fTlsKey       = config.String("tls.key", "", "tls key file")
	fPathRoot     = config.String("web.pathroot", "/", "path root")
	fDebugMode    = config.Bool("debug.enable", false, "debug模式")
	fDebugSession = config.String("debug.session", "", "debug模式万能session")
)

func main() {
	app.Start()
	http.HandleFunc("/debug/db/", HandleStats)
	http.HandleFunc("/exclude/", HandleExclude)
	http.HandleFunc("/storage/", storageHandle)
	server.LogIn(Login)
	server.LogOut(Logout)
	if err := server.Run(); err != nil {
		log.Err(err)
	}
}

func storageHandle(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	http.ServeFile(w, r, filepath.Join(GetFilePath(FileStorage), r.URL.Path[len("/storage/"):]))
}

func HandleStats(w http.ResponseWriter, r *http.Request) {

	s := db.Stats()
	b, _ := json.MarshalIndent(s, "", " ")
	_, _ = w.Write(b)
}
